#include "slist.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static node_t *node_create(int size)
{
    node_t *new_node = NULL;

    // 节点创建
    new_node = malloc(sizeof(node_t));
    if (new_node == NULL)
    {
        perror("node create failed...");
        goto err0;
    }
    memset(new_node, 0, sizeof(node_t));

    // 万能数据申请空间
    new_node->data = malloc(size);
    if (new_node->data == NULL)
    {
        perror("data create failed...");
        goto err1;
    }
    memset(new_node->data, 0, size);

    return new_node;


err1:
    free(new_node);
err0:
    return NULL;
}



slist_t *slist_create(int size)
{
    slist_t *s = NULL;

    // 参数检查
    if (size <= 0)
    {
        perror("size error...");
        goto err0;
    }

    // 创建节点空间
    s = malloc(sizeof(slist_t));
    if (NULL == s)
    {
        perror("slist_malloc failed...");
        goto err0;
    }
    memset(s, 0, sizeof(slist_t));

    // 写入数据
    s->tsize = size;
    s->p = NULL;
    s->count = 0;

    return s;

err0:
    return NULL;
}

int slist_append(slist_t *s, int *num)
{
    node_t *new_node = NULL;
    node_t *tmp = NULL;
    

    // 参数检查
    if (s == NULL)
    {
        perror("s = null?");
        goto err0;
    }

    // 申请节点
    new_node = node_create(s->tsize);
    if (new_node == NULL)
    {
        perror("node create failed...");
        goto err0;
    }

    // 写入数据
    // *((int *)(new_node->data)) = *num;
    memcpy(new_node->data, num, s->tsize);

    // 链表尾部插入 
    tmp = s->p;

    if (tmp == NULL)
    {
        s->p = new_node;
    }
    else 
    {
        while (tmp->next != NULL)
        {
            tmp = tmp->next;
        }
        tmp->next = new_node;
    }

    return 0;

err0:
    return -1;
}

int slist_traverse(slist_t *s, tp my_printf)
{
    node_t *tmp = NULL;

    // 参数检查
    if (s == NULL || my_printf == NULL)
    {
        perror("null....");
        goto err0;
    }

    tmp = s->p;

    // 链表遍历
    while (tmp != NULL)
    {
        my_printf(tmp->data);
        tmp = tmp->next;
    }


    return 0;

err0:
    return -1;
}

int slist_prepend(slist_t *s, void *num)
{
    node_t *new_node = NULL;
    node_t *tmp = NULL;

    // 参数检查
    if (s == NULL || num == NULL)
    {
        perror("null...");
        goto err0;
    }

    // 创建空间
    new_node = node_create(s->tsize);
    if (new_node == NULL)
    {
        perror("null...");
        goto err0;
    }

    // 写入数据
    memcpy(new_node->data, num, s->tsize);

    // 头部插入链表
    tmp = s->p;

    new_node->next = tmp;
    s->p = new_node;


    return 0;

err0:
    return -1;
}